﻿using CQIE.JonJack.Models;
using CQIE.JonJack.Models.Tabels;
using CQIE.JonJack.UtilitySource;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace CQIE.JonJack.QueryRenewalSystem.Controllers
{
    [Route("api/[controller]/[Action]")]
    [ApiController]
    public class PublicController : ControllerBase
    {
        //数据库操作对象
        private readonly _DbContext Db;
        private readonly IOptionsSnapshot<JWTSettings> jwtSettingsOpt;

        public PublicController(_DbContext db, IOptionsSnapshot<JWTSettings> jwtSettingsOpt)
        {
            Db = db;
            this.jwtSettingsOpt = jwtSettingsOpt;
        }

        [HttpPost]
        public string userLogin(string schoolNumber,string passWord)
        {

            string jwtResult = "";
            //进行登录比对
            User? user = Db.User.Where(u => u.SchoolNumber == schoolNumber && u.PassWord == passWord)
                                .SingleOrDefault();
            if (user != null)
            {
                //签发JWT登录证书
                //登录成功生成token
                List<Claim> claims = new();
                claims.Add(new Claim(ClaimTypes.NameIdentifier, user.SchoolNumber));//token中添加用户ID信息
                claims.Add(new Claim(ClaimTypes.Role, "Student"));//token中添加用户身份
                claims.Add(new Claim(ClaimTypes.Role, "Admain"));//token中添加用户身份
                                                                 //JWT的传输中不建议设置太多东西，不然耗费流量

                //接下来正式生成token
                string key = jwtSettingsOpt.Value.SecKey;//通过依赖注入获取密钥
                DateTime expire = DateTime.Now.AddSeconds(jwtSettingsOpt.Value.ExpireSecond);//获取过期时间
                byte[] secBytes = Encoding.UTF8.GetBytes(key);//密钥转二进制
                var secKey = new SymmetricSecurityKey(secBytes);
                var credentials = new SigningCredentials(secKey, SecurityAlgorithms.HmacSha256Signature);
                var tokenDescriptor = new JwtSecurityToken(claims: claims, expires: expire, signingCredentials: credentials);
                jwtResult = new JwtSecurityTokenHandler().WriteToken(tokenDescriptor);
                
            }
            return jwtResult;
        }
    }
}
